package drds.plus.executor.function.scalar.string;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

/**
 * <pre>
 * RIGHT(str,len)
 *
 * Returns the rightmost len characters from the string str, or NULL_KEY if any argument is NULL_KEY.
 *
 * mysql> SELECT RIGHT('foobarbar', 4);
 *         -> 'rbar'
 * </pre>
 *
 * @author mengshi.sunmengshi 2014年4月11日 下午6:11:40
 * @since 5.1.0
 */
public class Right extends ScalarFunction {

    public Type getReturnType() {
        return Type.StringType;
    }

    public String[] getFunctionNames() {
        return new String[]{"RIGHT"};
    }

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }
        String str = Type.StringType.convert(args[0]);
        Integer len = Type.IntegerType.convert(args[1]);
        if (len < 0) {
            return "";
        }
        return str.substring(str.length() - len);

    }
}
